package com.fablesoft.projectdatacollect.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.authentication.asynctask.AsyncM1Card;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.InOutResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.Log4jUtil;

import java.util.HashMap;
import java.util.Map;

import android_serialport_api.M1CardAPI;

public class FragmentSmartcard extends BaseFragment {

    private TextView tvSmartCardTip;
    private TextView tvCardNumValue;
    private TextView tvTip;
    private Button btReadCard;
    private Button btSubmit;
    private AsyncM1Card reader;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_smart_card, container, false);

        initView();
        initData();
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        tvSmartCardTip = (TextView) view.findViewById(R.id.tv_smart_card_tip);
        tvCardNumValue = (TextView) view.findViewById(R.id.card_num_value);
        tvTip = (TextView) view.findViewById(R.id.tv_tip);
        btReadCard = (Button) view.findViewById(R.id.bt_read_card);
        btSubmit = (Button) view.findViewById(R.id.submit);
        btLast = (Button) view.findViewById(R.id.last5);
        btReadCard.setOnClickListener(this);
        btSubmit.setOnClickListener(this);
        btLast.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        if (mActivity.result != null && mActivity.result.getData() != null
                && mActivity.result.getData().getOrgPersonBean() != null
                && !TextUtils.isEmpty(mActivity.result.getData().getOrgPersonBean().getRfidNo())) {
            tvCardNumValue.setText(mActivity.result.getData().getOrgPersonBean().getRfidNo());
        }
    }

    @Override
    public void onClick(View v) {
        if (isRepeatClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.bt_read_card:
                mHandler.sendEmptyMessageDelayed(CommonUtils.M1_CODE, 1000);
                break;
            case R.id.submit:
                btSubmit.setClickable(false);
                submitCheck();
                break;
            case R.id.last5:
                listener.onLast(5);
                break;
        }
    }

    @Override
    public void setSerialPort(boolean enable) {
        if (enable) {
            reader = new AsyncM1Card(MyApplication.getInstance().getHandlerThread().getLooper());
            reader.setOnReadCardNumListener(new AsyncM1Card.OnReadCardNumListener() {

                @Override
                public void onReadCardNumSuccess(String num) {
                    num = num.replaceAll(",", "").replaceAll("0x", "").replaceAll("\r", "").replaceAll("\n", "");
                    tvCardNumValue.setText(num);
                    mHandler.removeMessages(CommonUtils.M1_CODE);
                }

                @Override
                public void onReadCardNumFail(int confirmationCode) {
                    Log4jUtil.e("onReadCardNumFail, " + confirmationCode);
                    if (confirmationCode == M1CardAPI.Result.FIND_FAIL) {
                        Log.i("luzx", "M1卡" + getResources().getString(R.string.no_card_with_data));
                    } else if (confirmationCode == M1CardAPI.Result.TIME_OUT) {
                        Log.i("luzx", "M1卡" + getResources().getString(R.string.no_card_without_data));
                    } else if (confirmationCode == M1CardAPI.Result.OTHER_EXCEPTION) {
                        Log.i("luzx", "M1卡" + getResources().getString(R.string.find_card_exception));
                    }
                    mHandler.sendEmptyMessageDelayed(CommonUtils.M1_CODE, 1000);
                }
            });
        } else {
            mHandler.removeMessages(CommonUtils.M1_CODE);
            if (reader != null) {
                reader.removeCallbacksAndMessages(null);
            }
        }
    }

    public void submitCheck() {
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> mapParams = new HashMap<>();
        mapParams.put("idNo", mActivity.idNo);
        mapParams.put("orgId", MyApplication.getInstance().getOrgId());
        param.put("mapParams", mapParams);
        Log.d(CommonUtils.TAG_UPLOAD, "进出场校验开始......param = " + param);
        HttpThread thread = new HttpThread(Config.UPLOAD_CHECK_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.UPLOAD_CHECK;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        mActivity.onNotLogin(response);
                    }
                }, param, InOutResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(thread);
    }

    public void submitSmartCard() {
        String smardCard = tvCardNumValue.getText().toString();
        if (TextUtils.isEmpty(smardCard)) {
            Log.d(CommonUtils.TAG_UPLOAD, "智能卡信息为空，无法上传！");
            listener.onSubmitStatus(CommonUtils.UPLOAD_SMART_CARD, true, false);
            return;
        }
        Map<String, Object> param = new HashMap<>();
//        param.put("rfidCardId", smardCard);
//        param.put("id", baseInfo.getId());
        Log.d(CommonUtils.TAG_UPLOAD, "智能卡信息开始上传......param = " + param);
        HttpThread thread = new HttpThread(Config.UPLOAD_SMARTCARD_URL + "?rfidCardId=" + smardCard + "&id=" + mActivity.baseInfo.getId(),
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.UPLOAD_SMART_CARD;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        mActivity.onNotLogin(response);
                    }
                }, param, BaseResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(thread);
    }

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CommonUtils.M1_CODE:
                    reader.readCardNum();
                    break;
                case CommonUtils.UPLOAD_SMART_CARD:
                    BaseResponse smartResponse = (BaseResponse) msg.obj;
                    if (smartResponse == null) {
                        listener.onSubmitStatus(CommonUtils.UPLOAD_SMART_CARD, false, true);
                        return;
                    }
                    listener.onSubmitStatus(CommonUtils.UPLOAD_SMART_CARD, true, false);
                    break;
                case CommonUtils.UPLOAD_CHECK:
                    InOutResponse response = (InOutResponse) msg.obj;
                    if (response == null) {
                        Toast.makeText(mActivity,
                                R.string.request_error, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (response.getSuccess() && response.getRows() != null && response.getRows().size() > 0
                            && response.getRows().get(0).getInOutStatus() != null && response.getRows().get(0).getInOutStatus().equals("2")) {
                        tvTip.setText("人员已登记，请直接通过电脑操作人员进场。");
                        btSubmit.setClickable(false);
                        btLast.setClickable(false);
                    } else {
                        listener.onSubmitBaseInfo();
                    }
                    break;
            }
        }
    };

    public Button getBtSubmit() {
        return btSubmit;
    }
}
